home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / unix / volume22 / gawk2.11 / part07 < prev    next >
Encoding:
Internet Message Format  |  1990-06-07  |  54.2 KB

  1. Subject:  v22i093:  GNU AWK, version 2.11, Part07/16
  2. Newsgroups: comp.sources.unix
  3. Approved: rsalz@uunet.UU.NET
  4. X-Checksum-Snefru: b4023315 c1f70eee e7ef226e 4caa5b80
  5.  
  6. Submitted-by: "Arnold D. Robbins" <arnold@unix.cc.emory.edu>
  7. Posting-number: Volume 22, Issue 93
  8. Archive-name: gawk2.11/part07
  9.  
  10. #! /bin/sh
  11. # This is a shell archive.  Remove anything before this line, then feed it
  12. # into a shell via "sh file" or similar.  To overwrite existing files,
  13. # type "sh file -c".
  14. # The tool that generated this appeared in the comp.sources.unix newsgroup;
  15. # send mail to comp-sources-unix@uunet.uu.net if you want that tool.
  16. # Contents:  ./gawk.texinfo.06 ./missing.d/strerror.c
  17. #   ./missing.d/tmpnam.c
  18. # Wrapped by rsalz@litchi.bbn.com on Wed Jun  6 12:24:51 1990
  19. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  20. echo If this archive is complete, you will see the following message:
  21. echo '          "shar: End of archive 7 (of 16)."'
  22. if test -f './gawk.texinfo.06' -a "${1}" != "-c" ; then 
  23.   echo shar: Will not clobber existing file \"'./gawk.texinfo.06'\"
  24. else
  25.   echo shar: Extracting \"'./gawk.texinfo.06'\" \(49614 characters\)
  26.   sed "s/^X//" >'./gawk.texinfo.06' <<'END_OF_FILE'
  27. Xthe @code{BEGIN} rule was executed.  Some applications came to depend
  28. Xupon this ``feature''.  When @code{awk} was changed to be more consistent,
  29. Xthe @samp{-v} option was added to accomodate applications that depended
  30. Xupon this old behaviour.
  31. X
  32. XThe variable assignment feature is most useful for assigning to variables
  33. Xsuch as @code{RS}, @code{OFS}, and @code{ORS}, which control input and
  34. Xoutput formats, before scanning the data files.  It is also useful for
  35. Xcontrolling state if multiple passes are needed over a data file.  For
  36. Xexample:@refill
  37. X
  38. X@cindex multiple passes over data
  39. X@cindex passes, multiple
  40. X@example
  41. Xawk 'pass == 1  @{ @var{pass 1 stuff} @}
  42. X     pass == 2  @{ @var{pass 2 stuff} @}' pass=1 datafile pass=2 datafile
  43. X@end example
  44. X
  45. X@node AWKPATH Variable,, Other Arguments, Command Line
  46. X@section The @code{AWKPATH} Environment Variable
  47. X@cindex @code{AWKPATH} environment variable
  48. X@cindex search path
  49. X@cindex directory search
  50. X@cindex path, search
  51. X@c @cindex differences between @code{gawk} and @code{awk}
  52. X
  53. XThe previous section described how @code{awk} program files can be named
  54. Xon the command line with the @samp{-f} option.  In some @code{awk}
  55. Ximplementations, you must supply a precise path name for each program
  56. Xfile, unless the file is in the current directory.
  57. X
  58. XBut in @code{gawk}, if the file name supplied in the @samp{-f} option
  59. Xdoes not contain a @samp{/}, then @code{gawk} searches a list of
  60. Xdirectories (called the @dfn{search path}), one by one, looking for a
  61. Xfile with the specified name.
  62. X
  63. XThe search path is actually a string containing directory names
  64. Xseparated by colons.  @code{gawk} gets its search path from the
  65. X@code{AWKPATH} environment variable.  If that variable does not exist,
  66. X@code{gawk} uses the default path, which is
  67. X@samp{.:/usr/lib/awk:/usr/local/lib/awk}.@refill
  68. X
  69. XThe search path feature is particularly useful for building up libraries
  70. Xof useful @code{awk} functions.  The library files can be placed in a
  71. Xstandard directory that is in the default path, and then specified on
  72. Xthe command line with a short file name.  Otherwise, the full file name
  73. Xwould have to be typed for each file.
  74. X
  75. XPath searching is not done if @code{gawk} is in compatibility mode.
  76. X@xref{Command Line}.
  77. X
  78. X@strong{Note:} if you want files in the current directory to be found,
  79. Xyou must include the current directory in the path, either by writing
  80. X@file{.} as an entry in the path, or by writing a null entry in the
  81. Xpath.  (A null entry is indicated by starting or ending the path with a
  82. Xcolon, or by placing two colons next to each other (@samp{::}).)  If the
  83. Xcurrent directory is not included in the path, then files cannot be
  84. Xfound in the current directory.  This path search mechanism is identical
  85. Xto the shell's.
  86. X@c someday, @cite{The Bourne Again Shell}....
  87. X
  88. X@node Language History, Gawk Summary, Command Line, Top
  89. X@chapter The Evolution of the @code{awk} Language
  90. X
  91. XThis manual describes the GNU implementation of @code{awk}, which is patterned
  92. Xafter the System V Release 4 version.  Many @code{awk} users are only familiar
  93. Xwith the original @code{awk} implementation in Version 7 Unix, which is also
  94. Xthe basis for the version in Berkeley Unix.  This chapter briefly describes
  95. Xthe evolution of the @code{awk} language.
  96. X
  97. X@menu
  98. X* V7/S5R3.1::   The major changes between V7 and System V Release 3.1.
  99. X
  100. X* S5R4::        The minor changes between System V Releases 3.1 and 4.
  101. X
  102. X* S5R4/GNU::    The extensions in @code{gawk} not in System V Release 4.
  103. X@end menu
  104. X
  105. X@node V7/S5R3.1, S5R4, Language History, Language History
  106. X@section Major Changes Between V7 and S5R3.1
  107. X
  108. XThe @code{awk} language evolved considerably between the release of
  109. XVersion 7 Unix (1978) and the new version first made widely available in
  110. XSystem V Release 3.1 (1987).  This section summarizes the changes, with
  111. Xcross-references to further details.
  112. X
  113. X@itemize @bullet
  114. X@item
  115. XThe requirement for @samp{;} to separate rules on a line
  116. X(@pxref{Statements/Lines}).
  117. X
  118. X@item
  119. XUser-defined functions, and the @code{return} statement
  120. X(@pxref{User-defined}).
  121. X
  122. X@item
  123. XThe @code{delete} statement (@pxref{Delete}).
  124. X
  125. X@item
  126. XThe @code{do}-@code{while} statement (@pxref{Do Statement}).
  127. X
  128. X@item
  129. XThe built-in functions @code{atan2}, @code{cos}, @code{sin}, @code{rand} and
  130. X@code{srand} (@pxref{Numeric Functions}).
  131. X
  132. X@item
  133. XThe built-in functions @code{gsub}, @code{sub}, and @code{match}
  134. X(@pxref{String Functions}).
  135. X
  136. X@item
  137. XThe built-in functions @code{close} and @code{system} (@pxref{I/O
  138. XFunctions}).
  139. X
  140. X@item
  141. XThe @code{ARGC}, @code{ARGV}, @code{FNR}, @code{RLENGTH}, @code{RSTART},
  142. Xand @code{SUBSEP} built-in variables (@pxref{Built-in Variables}).
  143. X
  144. X@item
  145. XThe conditional expression using the operators @samp{?} and @samp{:}
  146. X(@pxref{Conditional Exp}).
  147. X
  148. X@item
  149. XThe exponentiation operator @samp{^} (@pxref{Arithmetic Ops}) and its
  150. Xassignment operator form @samp{^=} (@pxref{Assignment Ops}).@refill
  151. X
  152. X@item
  153. XC-compatible operator precedence, which breaks some old @code{awk}
  154. Xprograms (@pxref{Precedence}).
  155. X
  156. X@item
  157. XRegexps as the value of @code{FS} (@pxref{Field Separators}), or as the
  158. Xthird argument to the @code{split} function (@pxref{String
  159. XFunctions}).@refill
  160. X
  161. X@item
  162. XDynamic regexps as operands of the @samp{~} and @samp{!~} operators
  163. X(@pxref{Regexp Usage}).
  164. X
  165. X@item
  166. XEscape sequences (@pxref{Constants}) in regexps.@refill
  167. X
  168. X@item
  169. XThe escape sequences @samp{\b}, @samp{\f}, and @samp{\r}
  170. X(@pxref{Constants}).
  171. X
  172. X@item
  173. XRedirection of input for the @code{getline} function (@pxref{Getline}).
  174. X
  175. X@item
  176. XMultiple @code{BEGIN} and @code{END} rules (@pxref{BEGIN/END}).
  177. X
  178. X@item
  179. XSimulation of multidimensional arrays (@pxref{Multi-dimensional}).
  180. X@end itemize
  181. X
  182. X@node S5R4, S5R4/GNU, V7/S5R3.1, Language History
  183. X@section Minor Changes between S5R3.1 and S5R4
  184. X
  185. XThe System V Release 4 version of Unix @code{awk} added these features:
  186. X
  187. X@itemize @bullet
  188. X@item
  189. XThe @code{ENVIRON} variable (@pxref{Built-in Variables}).
  190. X
  191. X@item
  192. XMultiple @samp{-f} options on the command line (@pxref{Command Line}).
  193. X
  194. X@item
  195. XThe @samp{-v} option for assigning variables before program execution begins
  196. X(@pxref{Command Line}).
  197. X
  198. X@item
  199. XThe @samp{--} option for terminating command line options.
  200. X
  201. X@item
  202. XThe @samp{\a}, @samp{\v}, and @samp{\x} escape sequences (@pxref{Constants}).
  203. X
  204. X@item
  205. XA defined return value for the @code{srand} built-in function
  206. X(@pxref{Numeric Functions}).
  207. X
  208. X@item
  209. XThe @code{toupper} and @code{tolower} built-in string functions
  210. Xfor case translation (@pxref{String Functions}).
  211. X
  212. X@item
  213. XA cleaner specification for the @samp{%c} format-control letter in the
  214. X@code{printf} function (@pxref{Printf}).
  215. X
  216. X@item
  217. XThe use of constant regexps such as @code{/foo/} as expressions, where
  218. Xthey are equivalent to use of the matching operator, as in @code{$0 ~
  219. X/foo/}.
  220. X@end itemize
  221. X
  222. X@node S5R4/GNU, , S5R4, Language History
  223. X@section Extensions In @code{gawk} Not In S5R4
  224. X
  225. XThe GNU implementation, @code{gawk}, adds these features:
  226. X
  227. X@itemize @bullet
  228. X@item
  229. XThe @code{AWKPATH} environment variable for specifying a path search for
  230. Xthe @samp{-f} command line option (@pxref{Command Line}).
  231. X
  232. X@item
  233. XThe @samp{-C} and @samp{-V} command line options (@pxref{Command Line}).
  234. X
  235. X@item
  236. XThe @code{IGNORECASE} variable and its effects (@pxref{Case-sensitivity}).
  237. X
  238. X@item
  239. XThe @file{/dev/stdin}, @file{/dev/stdout}, @file{/dev/stderr}, and
  240. X@file{/dev/fd/@var{n}} file name interpretation (@pxref{Special Files}).
  241. X
  242. X@item
  243. XThe @samp{-c} option to turn off these extensions (@pxref{Command Line}).
  244. X
  245. X@item
  246. XThe @samp{-a} and @samp{-e} options to specify the syntax of regular
  247. Xexpressions that @code{gawk} will accept (@pxref{Command Line}).
  248. X@end itemize
  249. X
  250. X@node Gawk Summary, Sample Program, Language History, Top
  251. X@appendix @code{gawk} Summary
  252. X
  253. X@ignore
  254. XSee, man pages are good for something.  This chapter started life as the
  255. Xgawk.1 man page for 2.11.
  256. X@end ignore
  257. X
  258. XThis appendix provides a brief summary of the @code{gawk} command line and the
  259. X@code{awk} language.  It is designed to serve as ``quick reference.''  It is
  260. Xtherefore terse, but complete.
  261. X
  262. X@menu
  263. X* Command Line Summary::  Recapitulation of the command line.
  264. X* Language Summary::      A terse review of the language.
  265. X* Variables/Fields::      Variables, fields, and arrays.
  266. X* Rules Summary::         Patterns and Actions, and their component parts.
  267. X* Functions Summary::     Defining and calling functions.
  268. X@end menu
  269. X
  270. X@node Command Line Summary, Language Summary, Gawk Summary, Gawk Summary
  271. X@appendixsec Command Line Options Summary
  272. X
  273. XThe command line consists of options to @code{gawk} itself, the
  274. X@code{awk} program text (if not supplied via the @samp{-f} option), and
  275. Xvalues to be made available in the @code{ARGC} and @code{ARGV}
  276. Xpredefined @code{awk} variables:
  277. X
  278. X@example
  279. Xawk @r{[@code{-F@var{fs}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} '@var{program}' @var{file} @dots{}
  280. Xawk @r{[@code{-F@var{fs}}] @code{-f @var{source-file}} [@code{-f @var{source-file} @dots{}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} @var{file} @dots{}
  281. X@end example
  282. X
  283. XThe options that @code{gawk} accepts are:
  284. X
  285. X@table @code
  286. X@item -F@var{fs}
  287. XUse @var{fs} for the input field separator (the value of the @code{FS}
  288. Xpredefined variable).
  289. X
  290. X@item -f @var{program-file}
  291. XRead the @code{awk} program source from the file @var{program-file}, instead
  292. Xof from the first command line argument.
  293. X
  294. X@item -v @var{var}=@var{val}
  295. XAssign the variable @var{var} the value @var{val} before program execution
  296. Xbegins.
  297. X
  298. X@item -a
  299. XSpecifies use of traditional @code{awk} syntax for regular expressions.
  300. XThis means that @samp{\} can be used to quote regular expression
  301. Xoperators inside of square brackets, just as it can be outside of them.
  302. X
  303. X@item -e
  304. XSpecifies use of @code{egrep} syntax for regular expressions.  This
  305. Xmeans that @samp{\} does not serve as a quoting character inside of
  306. Xsquare brackets.
  307. X
  308. X@item -c
  309. XSpecifies compatibility mode, in which @code{gawk} extensions are turned
  310. Xoff.
  311. X
  312. X@item -V
  313. XPrint version information for this particular copy of @code{gawk} on the error
  314. Xoutput.  This option may disappear in a future version of @code{gawk}.
  315. X
  316. X@item -C
  317. XPrint the short version of the General Public License on the error
  318. Xoutput.  This option may disappear in a future version of @code{gawk}.
  319. X
  320. X@item --
  321. XSignal the end of options.  This is useful to allow further arguments to the
  322. X@code{awk} program itself to start with a @samp{-}.  This is mainly for
  323. Xconsistency with the argument parsing conventions of POSIX.
  324. X@end table
  325. X
  326. XAny other options are flagged as invalid, but are otherwise ignored.
  327. X@xref{Command Line}, for more details.
  328. X
  329. X@node Language Summary, Variables/Fields, Command Line Summary, Gawk Summary
  330. X@appendixsec Language Summary
  331. X
  332. XAn @code{awk} program consists of a sequence of pattern-action statements
  333. Xand optional function definitions.
  334. X
  335. X@example
  336. X@var{pattern}    @{ @var{action statements} @}
  337. X
  338. Xfunction @var{name}(@var{parameter list})     @{ @var{action statements} @}
  339. X@end example
  340. X
  341. X@code{gawk} first reads the program source from the
  342. X@var{program-file}(s) if specified, or from the first non-option
  343. Xargument on the command line.  The @samp{-f} option may be used multiple
  344. Xtimes on the command line.  @code{gawk} reads the program text from all
  345. Xthe @var{program-file} files, effectively concatenating them in the
  346. Xorder they are specified.  This is useful for building libraries of
  347. X@code{awk} functions, without having to include them in each new
  348. X@code{awk} program that uses them.  To use a library function in a file
  349. Xfrom a program typed in on the command line, specify @samp{-f /dev/tty};
  350. Xthen type your program, and end it with a @kbd{C-d}.  @xref{Command
  351. XLine}.
  352. X
  353. XThe environment variable @code{AWKPATH} specifies a search path to use
  354. Xwhen finding source files named with the @samp{-f} option.  If the
  355. Xvariable @code{AWKPATH} is not set, @code{gawk} uses the default path,
  356. X@samp{.:/usr/lib/awk:/usr/local/lib/awk}.  If a file name given to the
  357. X@samp{-f} option contains a @samp{/} character, no path search is
  358. Xperformed.  @xref{AWKPATH Variable}, for a full description of the
  359. X@code{AWKPATH} environment variable.@refill
  360. X
  361. X@code{gawk} compiles the program into an internal form, and then proceeds to
  362. Xread each file named in the @code{ARGV} array.  If there are no files named
  363. Xon the command line, @code{gawk} reads the standard input.
  364. X
  365. XIf a ``file'' named on the command line has the form
  366. X@samp{@var{var}=@var{val}}, it is treated as a variable assignment: the
  367. Xvariable @var{var} is assigned the value @var{val}.
  368. X
  369. XFor each line in the input, @code{gawk} tests to see if it matches any
  370. X@var{pattern} in the @code{awk} program.  For each pattern that the line
  371. Xmatches, the associated @var{action} is executed.
  372. X
  373. X@node Variables/Fields, Rules Summary, Language Summary, Gawk Summary
  374. X@appendixsec Variables and Fields
  375. X
  376. X@code{awk} variables are dynamic; they come into existence when they are
  377. Xfirst used.  Their values are either floating-point numbers or strings.
  378. X@code{awk} also has one-dimension arrays; multiple-dimensional arrays
  379. Xmay be simulated.  There are several predefined variables that
  380. X@code{awk} sets as a program runs; these are summarized below.
  381. X
  382. X@menu
  383. X* Fields Summary::      Input field splitting.
  384. X* Built-in Summary::    @code{awk}'s built-in variables.
  385. X* Arrays Summary::      Using arrays.
  386. X* Data Type Summary::   Values in @code{awk} are numbers or strings.
  387. X@end menu
  388. X
  389. X@node Fields Summary, Built-in Summary, Variables/Fields, Variables/Fields
  390. X@appendixsubsec Fields
  391. X
  392. XAs each input line is read, @code{gawk} splits the line into
  393. X@var{fields}, using the value of the @code{FS} variable as the field
  394. Xseparator.  If @code{FS} is a single character, fields are separated by
  395. Xthat character.  Otherwise, @code{FS} is expected to be a full regular
  396. Xexpression.  In the special case that @code{FS} is a single blank,
  397. Xfields are separated by runs of blanks and/or tabs.  Note that the value
  398. Xof @code{IGNORECASE} (@pxref{Case-sensitivity}) also affects how fields
  399. Xare split when @code{FS} is a regular expression.
  400. X
  401. XEach field in the input line may be referenced by its position, @code{$1},
  402. X@code{$2}, and so on.  @code{$0} is the whole line.  The value of a field may
  403. Xbe assigned to as well.  Field numbers need not be constants:
  404. X
  405. X@example
  406. Xn = 5
  407. Xprint $n
  408. X@end example
  409. X
  410. X@noindent
  411. Xprints the fifth field in the input line.  The variable @code{NF} is set to
  412. Xthe total number of fields in the input line.
  413. X
  414. XReferences to nonexistent fields (i.e., fields after @code{$NF}) return
  415. Xthe null-string.  However, assigning to a nonexistent field (e.g.,
  416. X@code{$(NF+2) = 5}) increases the value of @code{NF}, creates any
  417. Xintervening fields with the null string as their value, and causes the
  418. Xvalue of @code{$0} to be recomputed, with the fields being separated by
  419. Xthe value of @code{OFS}.@refill
  420. X
  421. X@xref{Reading Files}, for a full description of the way @code{awk} defines
  422. Xand uses fields.
  423. X
  424. X@node Built-in Summary, Arrays Summary, Fields Summary, Variables/Fields
  425. X@appendixsubsec Built-in Variables
  426. X
  427. X@code{awk}'s built-in variables are:
  428. X
  429. X@table @code
  430. X@item ARGC
  431. XThe number of command line arguments (not including options or the
  432. X@code{awk} program itself).
  433. X
  434. X@item ARGV
  435. XThe array of command line arguments.  The array is indexed from 0 to
  436. X@code{ARGC} - 1.  Dynamically changing the contents of @code{ARGV} can control
  437. Xthe files used for data.@refill
  438. X
  439. X@item ENVIRON
  440. XAn array containing the values of the environment variables.  The array
  441. Xis indexed by variable name, each element being the value of that
  442. Xvariable.  Thus, the environment variable @code{HOME} would be in
  443. X@code{ENVIRON["HOME"]}.  Its value might be @file{/u/close}.
  444. X
  445. XChanging this array does not affect the environment seen by programs
  446. Xwhich @code{gawk} spawns via redirection or the @code{system} function.
  447. X(This may change in a future version of @code{gawk}.)
  448. X
  449. XSome operating systems do not have environment variables.
  450. XThe array @code{ENVIRON} is empty when running on these systems.
  451. X
  452. X@item FILENAME
  453. XThe name of the current input file.  If no files are specified on the command
  454. Xline, the value of @code{FILENAME} is @samp{-}.
  455. X
  456. X@item FNR
  457. XThe input record number in the current input file.
  458. X
  459. X@item FS
  460. XThe input field separator, a blank by default.
  461. X
  462. X@item IGNORECASE
  463. XThe case-sensitivity flag for regular expression operations.  If
  464. X@code{IGNORECASE} has a nonzero value, then pattern matching in rules,
  465. Xfield splitting with @code{FS}, regular expression matching with
  466. X@samp{~} and @samp{!~}, and the @code{gsub}, @code{index}, @code{match},
  467. X@code{split} and @code{sub} predefined functions all ignore case
  468. Xwhen doing regular expression operations.@refill
  469. X
  470. X@item NF
  471. XThe number of fields in the current input record.
  472. X
  473. X@item NR
  474. XThe total number of input records seen so far.
  475. X
  476. X@item OFMT
  477. XThe output format for numbers, @code{"%.6g"} by default.
  478. X
  479. X@item OFS
  480. XThe output field separator, a blank by default.
  481. X
  482. X@item ORS
  483. XThe output record separator, by default a newline.
  484. X
  485. X@item RS
  486. XThe input record separator, by default a newline.  @code{RS} is exceptional
  487. Xin that only the first character of its string value is used for separating
  488. Xrecords.  If @code{RS} is set to the null string, then records are separated by
  489. Xblank lines.  When @code{RS} is set to the null string, then the newline
  490. Xcharacter always acts as a field separator, in addition to whatever value
  491. X@code{FS} may have.@refill
  492. X
  493. X@item RSTART
  494. XThe index of the first character matched by @code{match}; 0 if no match.
  495. X
  496. X@item RLENGTH
  497. XThe length of the string matched by @code{match}; @minus{}1 if no match.
  498. X
  499. X@item SUBSEP
  500. XThe string used to separate multiple subscripts in array elements, by
  501. Xdefault @code{"\034"}.
  502. X@end table
  503. X
  504. X@xref{Built-in Variables}.
  505. X
  506. X@node Arrays Summary, Data Type Summary, Built-in Summary, Variables/Fields
  507. X@appendixsubsec Arrays
  508. X
  509. XArrays are subscripted with an expression between square brackets
  510. X(@samp{[} and @samp{]}).  The expression may be either a number or
  511. Xa string.  Since arrays are associative, string indices are meaningful
  512. Xand are not converted to numbers.
  513. X
  514. XIf you use multiple expressions separated by commas inside the square
  515. Xbrackets, then the array subscript is a string consisting of the
  516. Xconcatenation of the individual subscript values, converted to strings,
  517. Xseparated by the subscript separator (the value of @code{SUBSEP}).
  518. X
  519. XThe special operator @code{in} may be used in an @code{if} or
  520. X@code{while} statement to see if an array has an index consisting of a
  521. Xparticular value.
  522. X
  523. X@group
  524. X@example
  525. Xif (val in array)
  526. X        print array[val]
  527. X@end example
  528. X@end group
  529. X
  530. XIf the array has multiple subscripts, use @code{(i, j, @dots{}) in array}
  531. Xto test for existence of an element.
  532. X
  533. XThe @code{in} construct may also be used in a @code{for} loop to iterate
  534. Xover all the elements of an array.  @xref{Scanning an Array}.
  535. X
  536. XAn element may be deleted from an array using the @code{delete} statement.
  537. X
  538. X@xref{Arrays}, for more detailed information.
  539. X
  540. X@node Data Type Summary, , Arrays Summary, Variables/Fields
  541. X@appendixsubsec Data Types
  542. X
  543. XThe value of an @code{awk} expression is always either a number
  544. Xor a string.
  545. X
  546. XCertain contexts (such as arithmetic operators) require numeric
  547. Xvalues.  They convert strings to numbers by interpreting the text
  548. Xof the string as a numeral.  If the string does not look like a
  549. Xnumeral, it converts to 0.
  550. X
  551. XCertain contexts (such as concatenation) require string values.
  552. XThey convert numbers to strings by effectively printing them.
  553. X
  554. XTo force conversion of a string value to a number, simply add 0
  555. Xto it.  If the value you start with is already a number, this
  556. Xdoes not change it.
  557. X
  558. XTo force conversion of a numeric value to a string, concatenate it with
  559. Xthe null string.
  560. X
  561. XThe @code{awk} language defines comparisons as being done numerically if
  562. Xpossible, otherwise one or both operands are converted to strings and
  563. Xa string comparison is performed.
  564. X
  565. XUninitialized variables have the string value @code{""} (the null, or
  566. Xempty, string).  In contexts where a number is required, this is
  567. Xequivalent to 0.
  568. X
  569. X@xref{Variables}, for more information on variable naming and initialization;
  570. X@pxref{Conversion}, for more information on how variable values are
  571. Xinterpreted.@refill
  572. X
  573. X@node Rules Summary, Functions Summary, Variables/Fields, Gawk Summary
  574. X@appendixsec Patterns and Actions
  575. X
  576. X@menu
  577. X* Pattern Summary::     Quick overview of patterns.
  578. X* Regexp Summary::      Quick overview of regular expressions.
  579. X* Actions Summary::     Quick overview of actions.
  580. X@end menu
  581. X
  582. XAn @code{awk} program is mostly composed of rules, each consisting of a
  583. Xpattern followed by an action.  The action is enclosed in @samp{@{} and
  584. X@samp{@}}.  Either the pattern may be missing, or the action may be
  585. Xmissing, but, of course, not both.  If the pattern is missing, the
  586. Xaction is executed for every single line of input.  A missing action is
  587. Xequivalent to this action,
  588. X
  589. X@example
  590. X@{ print @}
  591. X@end example
  592. X
  593. X@noindent
  594. Xwhich prints the entire line.
  595. X
  596. XComments begin with the @samp{#} character, and continue until the end of the
  597. Xline.  Blank lines may be used to separate statements.  Normally, a statement
  598. Xends with a newline, however, this is not the case for lines ending in a
  599. X@samp{,}, @samp{@{}, @samp{?}, @samp{:}, @samp{&&}, or @samp{||}.  Lines
  600. Xending in @code{do} or @code{else} also have their statements automatically
  601. Xcontinued on the following line.  In other cases, a line can be continued by
  602. Xending it with a @samp{\}, in which case the newline is ignored.@refill
  603. X
  604. XMultiple statements may be put on one line by separating them with a @samp{;}.
  605. XThis applies to both the statements within the action part of a rule (the
  606. Xusual case), and to the rule statements themselves.
  607. X
  608. X@xref{Comments}, for information on @code{awk}'s commenting convention;
  609. X@pxref{Statements/Lines}, for a description of the line continuation
  610. Xmechanism in @code{awk}.
  611. X
  612. X@node Pattern Summary, Regexp Summary, Rules Summary, Rules Summary
  613. X@appendixsubsec Patterns
  614. X
  615. X@code{awk} patterns may be one of the following:
  616. X
  617. X@example
  618. X/@var{regular expression}/
  619. X@var{relational expression}
  620. X@var{pattern} && @var{pattern}
  621. X@var{pattern} || @var{pattern}
  622. X@var{pattern} ? @var{pattern} : @var{pattern}
  623. X(@var{pattern})
  624. X! @var{pattern}
  625. X@var{pattern1}, @var{pattern2}
  626. XBEGIN
  627. XEND
  628. X@end example
  629. X
  630. X@code{BEGIN} and @code{END} are two special kinds of patterns that are not
  631. Xtested against the input.  The action parts of all @code{BEGIN} rules are
  632. Xmerged as if all the statements had been written in a single @code{BEGIN}
  633. Xrule.  They are executed before any of the input is read.  Similarly, all the
  634. X@code{END} rules are merged, and executed when all the input is exhausted (or
  635. Xwhen an @code{exit} statement is executed).  @code{BEGIN} and @code{END}
  636. Xpatterns cannot be combined with other patterns in pattern expressions.
  637. X@code{BEGIN} and @code{END} rules cannot have missing action parts.@refill
  638. X
  639. XFor @samp{/@var{regular-expression}/} patterns, the associated statement is
  640. Xexecuted for each input line that matches the regular expression.  Regular
  641. Xexpressions are the same as those in @code{egrep}, and are summarized below.
  642. X
  643. XA @var{relational expression} may use any of the operators defined below in
  644. Xthe section on actions.  These generally test whether certain fields match
  645. Xcertain regular expressions.
  646. X
  647. XThe @samp{&&}, @samp{||}, and @samp{!} operators are logical ``and'',
  648. Xlogical ``or'', and logical ``not'', respectively, as in C.  They do
  649. Xshort-circuit evaluation, also as in C, and are used for combining more
  650. Xprimitive pattern expressions.  As in most languages, parentheses may be
  651. Xused to change the order of evaluation.
  652. X
  653. XThe @samp{?:} operator is like the same operator in C.  If the first
  654. Xpattern matches, then the second pattern is matched against the input
  655. Xrecord; otherwise, the third is matched.  Only one of the second and
  656. Xthird patterns is matched.
  657. X
  658. XThe @samp{@var{pattern1}, @var{pattern2}} form of a pattern is called a
  659. Xrange pattern.  It matches all input lines starting with a line that
  660. Xmatches @var{pattern1}, and continuing until a line that matches
  661. X@var{pattern2}, inclusive.  A range pattern cannot be used as an operand
  662. Xto any of the pattern operators.
  663. X
  664. X@xref{Patterns}, for a full description of the pattern part of @code{awk}
  665. Xrules.
  666. X
  667. X@node Regexp Summary, Actions Summary, Pattern Summary, Rules Summary
  668. X@appendixsubsec Regular Expressions
  669. X
  670. XRegular expressions are the extended kind found in @code{egrep}.
  671. XThey are composed of characters as follows:
  672. X
  673. X@table @code
  674. X@item @var{c}
  675. Xmatches the character @var{c} (assuming @var{c} is a character with no
  676. Xspecial meaning in regexps).
  677. X
  678. X@item \@var{c}
  679. Xmatches the literal character @var{c}.
  680. X
  681. X@item .
  682. Xmatches any character except newline.
  683. X
  684. X@item ^
  685. Xmatches the beginning of a line or a string.
  686. X
  687. X@item $
  688. Xmatches the end of a line or a string.
  689. X
  690. X@item [@var{abc}@dots{}]
  691. Xmatches any of the characters @var{abc}@dots{} (character class).
  692. X
  693. X@item [^@var{abc}@dots{}]
  694. Xmatches any character except @var{abc}@dots{} and newline (negated
  695. Xcharacter class).
  696. X
  697. X@item @var{r1}|@var{r2}
  698. Xmatches either @var{r1} or @var{r2} (alternation).
  699. X
  700. X@item @var{r1r2}
  701. Xmatches @var{r1}, and then @var{r2} (concatenation).
  702. X
  703. X@item @var{r}+
  704. Xmatches one or more @var{r}'s.
  705. X
  706. X@item @var{r}*
  707. Xmatches zero or more @var{r}'s. 
  708. X
  709. X@item @var{r}?
  710. Xmatches zero or one @var{r}'s. 
  711. X
  712. X@item (@var{r})
  713. Xmatches @var{r} (grouping).
  714. X@end table
  715. X
  716. X@xref{Regexp}, for a more detailed explanation of regular expressions.
  717. X
  718. XThe escape sequences allowed in string constants are also valid in
  719. Xregular expressions (@pxref{Constants}).
  720. X
  721. X@node Actions Summary, , Regexp Summary, Rules Summary
  722. X@appendixsubsec Actions
  723. X
  724. XAction statements are enclosed in braces, @samp{@{} and @samp{@}}.
  725. XAction statements consist of the usual assignment, conditional, and looping
  726. Xstatements found in most languages.  The operators, control statements,
  727. Xand input/output statements available are patterned after those in C.
  728. X
  729. X@menu
  730. X* Operator Summary::            @code{awk} operators.
  731. X* Control Flow Summary::        The control statements.
  732. X* I/O Summary::                 The I/O statements.
  733. X* Printf Summary::              A summary of @code{printf}.
  734. X* Special File Summary::        Special file names interpreted internally.
  735. X* Numeric Functions Summary::   Built-in numeric functions.
  736. X* String Functions Summary::    Built-in string functions.
  737. X* String Constants Summary::    Escape sequences in strings.
  738. X@end menu
  739. X
  740. X@node Operator Summary, Control Flow Summary, Actions Summary, Actions Summary
  741. X@appendixsubsubsec Operators
  742. X
  743. XThe operators in @code{awk}, in order of increasing precedence, are
  744. X
  745. X@table @code
  746. X@item = += -= *= /= %= ^=
  747. XAssignment.  Both absolute assignment (@code{@var{var}=@var{value}})
  748. Xand operator assignment (the other forms) are supported.
  749. X
  750. X@item ?:
  751. XA conditional expression, as in C.  This has the form @code{@var{expr1} ?
  752. X@var{expr2} : @var{expr3}}.  If @var{expr1} is true, the value of the
  753. Xexpression is @var{expr2}; otherwise it is @var{expr3}.  Only one of
  754. X@var{expr2} and @var{expr3} is evaluated.@refill
  755. X
  756. X@item ||
  757. XLogical ``or''.
  758. X
  759. X@item &&
  760. XLogical ``and''.
  761. X
  762. X@item ~ !~
  763. XRegular expression match, negated match.
  764. X
  765. X@item < <= > >= != ==
  766. XThe usual relational operators.
  767. X
  768. X@item @var{blank}
  769. XString concatenation.
  770. X
  771. X@item + -
  772. XAddition and subtraction.
  773. X
  774. X@item * / %
  775. XMultiplication, division, and modulus.
  776. X
  777. X@item + - !
  778. XUnary plus, unary minus, and logical negation.
  779. X
  780. X@item ^
  781. XExponentiation (@samp{**} may also be used, and @samp{**=} for the assignment
  782. Xoperator).
  783. X
  784. X@item ++ --
  785. XIncrement and decrement, both prefix and postfix.
  786. X
  787. X@item $
  788. XField reference.
  789. X@end table
  790. X
  791. X@xref{Expressions}, for a full description of all the operators listed
  792. Xabove.  @xref{Fields}, for a description of the field reference operator.
  793. X
  794. X@node Control Flow Summary, I/O Summary, Operator Summary, Actions Summary
  795. X@appendixsubsubsec Control Statements
  796. X
  797. XThe control statements are as follows:
  798. X
  799. X@example
  800. Xif (@var{condition}) @var{statement} @r{[} else @var{statement} @r{]}
  801. Xwhile (@var{condition}) @var{statement}
  802. Xdo @var{statement} while (@var{condition})
  803. Xfor (@var{expr1}; @var{expr2}; @var{expr3}) @var{statement}
  804. Xfor (@var{var} in @var{array}) @var{statement}
  805. Xbreak
  806. Xcontinue
  807. Xdelete @var{array}[@var{index}]
  808. Xexit @r{[} @var{expression} @r{]}
  809. X@{ @var{statements} @}
  810. X@end example
  811. X
  812. X@xref{Statements}, for a full description of all the control statements
  813. Xlisted above.
  814. X
  815. X@node I/O Summary, Printf Summary, Control Flow Summary, Actions Summary
  816. X@appendixsubsubsec I/O Statements
  817. X
  818. XThe input/output statements are as follows:
  819. X
  820. X@table @code
  821. X@item getline
  822. XSet @code{$0} from next input record; set @code{NF}, @code{NR}, @code{FNR}.
  823. X
  824. X@item getline <@var{file}
  825. XSet @code{$0} from next record of @var{file}; set @code{NF}.
  826. X
  827. X@item getline @var{var}
  828. XSet @var{var} from next input record; set @code{NF}, @code{FNR}.
  829. X
  830. X@item getline @var{var} <@var{file}
  831. XSet @var{var} from next record of @var{file}.
  832. X
  833. X@item next
  834. XStop processing the current input record.  The next input record is read and
  835. Xprocessing starts over with the first pattern in the @code{awk} program.
  836. XIf the end of the input data is reached, the @code{END} rule(s), if any,
  837. Xare executed.
  838. X
  839. X@item print
  840. XPrints the current record.
  841. X
  842. X@item print @var{expr-list}
  843. XPrints expressions.
  844. X
  845. X@item print @var{expr-list} > @var{file}
  846. XPrints expressions on @var{file}.
  847. X
  848. X@item printf @var{fmt, expr-list}
  849. XFormat and print.
  850. X
  851. X@item printf @var{fmt, expr-list} > file
  852. XFormat and print on @var{file}.
  853. X@end table
  854. X
  855. XOther input/output redirections are also allowed.  For @code{print} and
  856. X@code{printf}, @samp{>> @var{file}} appends output to the @var{file},
  857. Xwhile @samp{| @var{command}} writes on a pipe.  In a similar fashion,
  858. X@samp{@var{command} | getline} pipes input into @code{getline}.
  859. X@code{getline} returns 0 on end of file, and @minus{}1 on an error.@refill
  860. X
  861. X@xref{Getline}, for a full description of the @code{getline} statement.
  862. X@xref{Printing}, for a full description of @code{print} and
  863. X@code{printf}.  Finally, @pxref{Next Statement}, for a description of
  864. Xhow the @code{next} statement works.@refill
  865. X
  866. X@node Printf Summary, Special File Summary, I/O Summary, Actions Summary
  867. X@appendixsubsubsec @code{printf} Summary
  868. X
  869. XThe @code{awk} @code{printf} statement and @code{sprintf} function
  870. Xaccept the following conversion specification formats:
  871. X
  872. X@table @code
  873. X@item %c
  874. XAn ASCII character.  If the argument used for @samp{%c} is numeric, it is
  875. Xtreated as a character and printed.  Otherwise, the argument is assumed to
  876. Xbe a string, and the only first character of that string is printed.
  877. X
  878. X@item %d
  879. XA decimal number (the integer part).
  880. X
  881. X@item %i
  882. XAlso a decimal integer.
  883. X
  884. X@item %e
  885. XA floating point number of the form
  886. X@samp{@r{[}-@r{]}d.ddddddE@r{[}+-@r{]}dd}.@refill
  887. X
  888. X@item %f
  889. XA floating point number of the form
  890. X@r{[}@code{-}@r{]}@code{ddd.dddddd}.
  891. X
  892. X@item %g
  893. XUse @samp{%e} or @samp{%f} conversion, whichever is shorter, with
  894. Xnonsignificant zeros suppressed.
  895. X
  896. X@item %o
  897. XAn unsigned octal number (again, an integer).
  898. X
  899. X@item %s
  900. XA character string.
  901. X
  902. X@item %x
  903. XAn unsigned hexadecimal number (an integer).
  904. X
  905. X@item %X
  906. XLike @samp{%x}, except use @samp{A} through @samp{F} instead of @samp{a}
  907. Xthrough @samp{f} for decimal 10 through 15.@refill
  908. X
  909. X@item %%
  910. XA single @samp{%} character; no argument is converted.
  911. X@end table
  912. X
  913. XThere are optional, additional parameters that may lie between the @samp{%}
  914. Xand the control letter:
  915. X
  916. X@table @code
  917. X@item -
  918. XThe expression should be left-justified within its field.
  919. X
  920. X@item @var{width}
  921. XThe field should be padded to this width.  If @var{width} has a leading zero,
  922. Xthen the field is padded with zeros.  Otherwise it is padded with blanks.
  923. X
  924. X@item .@var{prec}
  925. XA number indicating the maximum width of strings or digits to the right
  926. Xof the decimal point.
  927. X@end table
  928. X
  929. X@xref{Printf}, for examples and for a more detailed description.
  930. X
  931. X@node Special File Summary, Numeric Functions Summary, Printf Summary, Actions Summary
  932. X@appendixsubsubsec Special File Names
  933. X
  934. XWhen doing I/O redirection from either @code{print} or @code{printf} into a
  935. Xfile, or via @code{getline} from a file, @code{gawk} recognizes certain special
  936. Xfile names internally.  These file names allow access to open file descriptors
  937. Xinherited from @code{gawk}'s parent process (usually the shell).  The
  938. Xfile names are:
  939. X
  940. X@table @file
  941. X@item /dev/stdin
  942. XThe standard input.
  943. X
  944. X@item /dev/stdout
  945. XThe standard output.
  946. X
  947. X@item /dev/stderr
  948. XThe standard error output.
  949. X
  950. X@item /dev/fd/@var{n}
  951. XThe file denoted by the open file descriptor @var{n}.
  952. X@end table
  953. X
  954. X@noindent
  955. XThese file names may also be used on the command line to name data files.
  956. X
  957. X@xref{Special Files}, for a longer description that provides the motivation
  958. Xfor this feature.
  959. X
  960. X@node Numeric Functions Summary, String Functions Summary, Special File Summary, Actions Summary
  961. X@appendixsubsubsec Numeric Functions
  962. X
  963. X@code{awk} has the following predefined arithmetic functions:
  964. X
  965. X@table @code
  966. X@item atan2(@var{y}, @var{x})
  967. Xreturns the arctangent of @var{y/x} in radians.
  968. X
  969. X@item cos(@var{expr})
  970. Xreturns the cosine in radians.
  971. X
  972. X@item exp(@var{expr})
  973. Xthe exponential function.
  974. X
  975. X@item int(@var{expr})
  976. Xtruncates to integer.
  977. X
  978. X@item log(@var{expr})
  979. Xthe natural logarithm function.
  980. X
  981. X@item rand()
  982. Xreturns a random number between 0 and 1.
  983. X
  984. X@item sin(@var{expr})
  985. Xreturns the sine in radians.
  986. X
  987. X@item sqrt(@var{expr})
  988. Xthe square root function.
  989. X
  990. X@item srand(@var{expr})
  991. Xuse @var{expr} as a new seed for the random number generator.  If no @var{expr}
  992. Xis provided, the time of day is used.  The return value is the previous
  993. Xseed for the random number generator.
  994. X@end table
  995. X
  996. X@node String Functions Summary, String Constants Summary, Numeric Functions Summary, Actions Summary
  997. X@appendixsubsubsec String Functions
  998. X
  999. X@code{awk} has the following predefined string functions:
  1000. X
  1001. X@table @code
  1002. X@item gsub(@var{r}, @var{s}, @var{t})
  1003. Xfor each substring matching the regular expression @var{r} in the string
  1004. X@var{t}, substitute the string @var{s}, and return the number of substitutions.
  1005. XIf @var{t} is not supplied, use @code{$0}.
  1006. X
  1007. X@item index(@var{s}, @var{t})
  1008. Xreturns the index of the string @var{t} in the string @var{s}, or 0 if
  1009. X@var{t} is not present.
  1010. X
  1011. X@item length(@var{s})
  1012. Xreturns the length of the string @var{s}.
  1013. X
  1014. X@item match(@var{s}, @var{r})
  1015. Xreturns the position in @var{s} where the regular expression @var{r}
  1016. Xoccurs, or 0 if @var{r} is not present, and sets the values of @code{RSTART}
  1017. Xand @code{RLENGTH}.
  1018. X
  1019. X@item split(@var{s}, @var{a}, @var{r})
  1020. Xsplits the string @var{s} into the array @var{a} on the regular expression
  1021. X@var{r}, and returns the number of fields.  If @var{r} is omitted, @code{FS}
  1022. Xis used instead.
  1023. X
  1024. X@item sprintf(@var{fmt}, @var{expr-list})
  1025. Xprints @var{expr-list} according to @var{fmt}, and returns the resulting string.
  1026. X
  1027. X@item sub(@var{r}, @var{s}, @var{t})
  1028. Xthis is just like @code{gsub}, but only the first matching substring is
  1029. Xreplaced.
  1030. X
  1031. X@item substr(@var{s}, @var{i}, @var{n})
  1032. Xreturns the @var{n}-character substring of @var{s} starting at @var{i}.
  1033. XIf @var{n} is omitted, the rest of @var{s} is used.
  1034. X
  1035. X@item tolower(@var{str})
  1036. Xreturns a copy of the string @var{str}, with all the upper-case characters in
  1037. X@var{str} translated to their corresponding lower-case counterparts.
  1038. XNonalphabetic characters are left unchanged.
  1039. X
  1040. X@item toupper(@var{str})
  1041. Xreturns a copy of the string @var{str}, with all the lower-case characters in
  1042. X@var{str} translated to their corresponding upper-case counterparts.
  1043. XNonalphabetic characters are left unchanged.
  1044. X
  1045. X@item system(@var{cmd-line})
  1046. XExecute the command @var{cmd-line}, and return the exit status.
  1047. X@end table
  1048. X
  1049. X@xref{Built-in}, for a description of all of @code{awk}'s built-in functions.
  1050. X
  1051. X@node String Constants Summary, , String Functions Summary, Actions Summary
  1052. X@appendixsubsubsec String Constants
  1053. X
  1054. XString constants in @code{awk} are sequences of characters enclosed
  1055. Xbetween double quotes (@code{"}).  Within strings, certain @dfn{escape sequences}
  1056. Xare recognized, as in C.  These are:
  1057. X
  1058. X@table @code
  1059. X@item \\
  1060. XA literal backslash.
  1061. X
  1062. X@item \a
  1063. XThe ``alert'' character; usually the ASCII BEL character.
  1064. X
  1065. X@item \b
  1066. XBackspace.
  1067. X
  1068. X@item \f
  1069. XFormfeed.
  1070. X
  1071. X@item \n
  1072. XNewline.
  1073. X
  1074. X@item \r
  1075. XCarriage return.
  1076. X
  1077. X@item \t
  1078. XHorizontal tab.
  1079. X
  1080. X@item \v
  1081. XVertical tab.
  1082. X
  1083. X@item \x@var{hex digits}
  1084. XThe character represented by the string of hexadecimal digits following
  1085. Xthe @samp{\x}.  As in ANSI C, all following hexadecimal digits are
  1086. Xconsidered part of the escape sequence.  (This feature should tell us
  1087. Xsomething about language design by committee.)  E.g., @code{"\x1B"} is a
  1088. Xstring containing the ASCII ESC (escape) character.
  1089. X
  1090. X@item \@var{ddd}
  1091. XThe character represented by the 1-, 2-, or 3-digit sequence of octal
  1092. Xdigits.  Thus, @code{"\033"} is also a string containing the ASCII ESC
  1093. X(escape) character.
  1094. X
  1095. X@item \@var{c}
  1096. XThe literal character @var{c}.
  1097. X@end table
  1098. X
  1099. XThe escape sequences may also be used inside constant regular expressions
  1100. X(e.g., the regexp @code{@w{/[@ \t\f\n\r\v]/}} matches whitespace
  1101. Xcharacters).@refill
  1102. X
  1103. X@xref{Constants}.
  1104. X
  1105. X@node Functions Summary, , Rules Summary, Gawk Summary
  1106. X@appendixsec Functions
  1107. X
  1108. XFunctions in @code{awk} are defined as follows:
  1109. X
  1110. X@example
  1111. Xfunction @var{name}(@var{parameter list}) @{ @var{statements} @}
  1112. X@end example
  1113. X
  1114. XActual parameters supplied in the function call are used to instantiate
  1115. Xthe formal parameters declared in the function.  Arrays are passed by
  1116. Xreference, other variables are passed by value.
  1117. X
  1118. XIf there are fewer arguments passed than there are names in @var{parameter-list},
  1119. Xthe extra names are given the null string as value.  Extra names have the
  1120. Xeffect of local variables.
  1121. X
  1122. XThe open-parenthesis in a function call must immediately follow the
  1123. Xfunction name, without any intervening white space.  This is to avoid a
  1124. Xsyntactic ambiguity with the concatenation operator.
  1125. X
  1126. XThe word @code{func} may be used in place of @code{function}.
  1127. X
  1128. X@xref{User-defined}, for a more complete description.
  1129. X
  1130. X@node Sample Program, Notes, Gawk Summary, Top
  1131. X@appendix Sample Program
  1132. X
  1133. XThe following example is a complete @code{awk} program, which prints
  1134. Xthe number of occurrences of each word in its input.  It illustrates the
  1135. Xassociative nature of @code{awk} arrays by using strings as subscripts.  It
  1136. Xalso demonstrates the @samp{for @var{x} in @var{array}} construction.
  1137. XFinally, it shows how @code{awk} can be used in conjunction with other
  1138. Xutility programs to do a useful task of some complexity with a minimum of
  1139. Xeffort.  Some explanations follow the program listing.@refill
  1140. X
  1141. X@example
  1142. Xawk '
  1143. X# Print list of word frequencies
  1144. X@{
  1145. X    for (i = 1; i <= NF; i++)
  1146. X        freq[$i]++
  1147. X@}
  1148. X
  1149. XEND @{
  1150. X    for (word in freq)
  1151. X        printf "%s\t%d\n", word, freq[word]
  1152. X@}'
  1153. X@end example
  1154. X
  1155. XThe first thing to notice about this program is that it has two rules.  The
  1156. Xfirst rule, because it has an empty pattern, is executed on every line of
  1157. Xthe input.  It uses @code{awk}'s field-accessing mechanism (@pxref{Fields})
  1158. Xto pick out the individual words from the line, and the built-in variable
  1159. X@code{NF} (@pxref{Built-in Variables}) to know how many fields are available.
  1160. X
  1161. XFor each input word, an element of the array @code{freq} is incremented to
  1162. Xreflect that the word has been seen an additional time.@refill
  1163. X
  1164. XThe second rule, because it has the pattern @code{END}, is not executed
  1165. Xuntil the input has been exhausted.  It prints out the contents of the
  1166. X@code{freq} table that has been built up inside the first action.@refill
  1167. X
  1168. XNote that this program has several problems that would prevent it from being
  1169. Xuseful by itself on real text files:@refill
  1170. X
  1171. X@itemize @bullet
  1172. X@item
  1173. XWords are detected using the @code{awk} convention that fields are
  1174. Xseparated by whitespace and that other characters in the input (except
  1175. Xnewlines) don't have any special meaning to @code{awk}.  This means that
  1176. Xpunctuation characters count as part of words.@refill
  1177. X
  1178. X@item
  1179. XThe @code{awk} language considers upper and lower case characters to be
  1180. Xdistinct.  Therefore, @samp{foo} and @samp{Foo} are not treated by this
  1181. Xprogram as the same word.  This is undesirable since in normal text, words
  1182. Xare capitalized if they begin sentences, and a frequency analyzer should not
  1183. Xbe sensitive to that.@refill
  1184. X
  1185. X@item
  1186. XThe output does not come out in any useful order.  You're more likely to be
  1187. Xinterested in which words occur most frequently, or having an alphabetized
  1188. Xtable of how frequently each word occurs.@refill
  1189. X@end itemize
  1190. X
  1191. XThe way to solve these problems is to use other system utilities to
  1192. Xprocess the input and output of the @code{awk} script.  Suppose the
  1193. Xscript shown above is saved in the file @file{frequency.awk}.  Then the
  1194. Xshell command:@refill
  1195. X
  1196. X@example
  1197. Xtr A-Z a-z < file1 | tr -cd 'a-z\012' \
  1198. X  | awk -f frequency.awk \
  1199. X  | sort +1 -nr
  1200. X@end example
  1201. X
  1202. X@noindent
  1203. Xproduces a table of the words appearing in @file{file1} in order of
  1204. Xdecreasing frequency.
  1205. X
  1206. XThe first @code{tr} command in this pipeline translates all the upper case
  1207. Xcharacters in @file{file1} to lower case.  The second @code{tr} command
  1208. Xdeletes all the characters in the input except lower case characters and
  1209. Xnewlines.  The second argument to the second @code{tr} is quoted to protect
  1210. Xthe backslash in it from being interpreted by the shell.  The @code{awk}
  1211. Xprogram reads this suitably massaged data and produces a word frequency
  1212. Xtable, which is not ordered.
  1213. X
  1214. XThe @code{awk} script's output is now sorted by the @code{sort} command and
  1215. Xprinted on the terminal.  The options given to @code{sort} in this example
  1216. Xspecify to sort by the second field of each input line (skipping one field),
  1217. Xthat the sort keys should be treated as numeric quantities (otherwise
  1218. X@samp{15} would come before @samp{5}), and that the sorting should be done
  1219. Xin descending (reverse) order.@refill
  1220. X
  1221. XSee the general operating system documentation for more information on how
  1222. Xto use the @code{tr} and @code{sort} commands.@refill
  1223. X
  1224. X@ignore
  1225. X@strong{ADR: I have some more substantial programs courtesy of Rick Adams
  1226. Xat UUNET.  I am planning on incorporating those either in addition to or
  1227. Xinstead of this program.}
  1228. X
  1229. X@strong{I would also like to incorporate the general @code{translate}
  1230. Xfunction that I have written.}
  1231. X@end ignore
  1232. X
  1233. X@node Notes, Glossary, Sample Program, Top
  1234. X@appendix Implementation Notes
  1235. X
  1236. XThis appendix contains information mainly of interest to implementors and
  1237. Xmaintainers of @code{gawk}.  Everything in it applies specifically to
  1238. X@code{gawk}, and not to other implementations.
  1239. X
  1240. X@menu
  1241. X* Compatibility Mode::   How to disable certain @code{gawk} extensions.
  1242. X
  1243. X* Future Extensions::    New features we may implement soon.
  1244. X
  1245. X* Improvements::         Suggestions for improvements by volunteers.
  1246. X@end menu
  1247. X
  1248. X@node Compatibility Mode, Future Extensions, Notes, Notes
  1249. X@appendixsec Downwards Compatibility and Debugging
  1250. X
  1251. X@xref{S5R4/GNU}, for a summary of the GNU extensions to the @code{awk}
  1252. Xlanguage and program.  All of these features can be turned off either by
  1253. Xcompiling @code{gawk} with @samp{-DSTRICT} (not recommended), or by
  1254. Xinvoking @code{gawk} with the @samp{-c} option.@refill
  1255. X
  1256. XIf @code{gawk} is compiled for debugging with @samp{-DDEBUG}, then there
  1257. Xare two more options available on the command line.
  1258. X
  1259. X@table @samp
  1260. X@item -d
  1261. XPrint out debugging information during execution.
  1262. X
  1263. X@item -D
  1264. XPrint out the parse stack information as the program is being parsed.
  1265. X@end table
  1266. X
  1267. XBoth of these options are intended only for serious @code{gawk} developers,
  1268. Xand not for the casual user.  They probably have not even been compiled into
  1269. Xyour version of @code{gawk}, since they slow down execution.
  1270. X
  1271. XThe code for recognizing special file names such as @file{/dev/stdin}
  1272. Xcan be disabled at compile time with @samp{-DNO_DEV_FD}, or with
  1273. X@samp{-DSTRICT}.@refill
  1274. X
  1275. X@node Future Extensions, Improvements, Compatibility Mode, Notes
  1276. X@appendixsec Probable Future Extensions
  1277. X
  1278. XThis section briefly lists extensions that indicate the directions we are
  1279. Xcurrently considering for @code{gawk}.
  1280. X
  1281. X@table @asis
  1282. X@item ANSI C compatible @code{printf}
  1283. XThe @code{printf} and @code{sprintf} functions may be enhanced to be
  1284. Xfully compatible with the specification for the @code{printf} family
  1285. Xof functions in ANSI C.@refill
  1286. X
  1287. X@item @code{RS} as a regexp
  1288. XThe meaning of @code{RS} may be generalized along the lines of @code{FS}.
  1289. X
  1290. X@item Control of subprocess environment
  1291. XChanges made in @code{gawk} to the array @code{ENVIRON} may be
  1292. Xpropagated to subprocesses run by @code{gawk}.
  1293. X
  1294. X@item Data bases
  1295. XIt may be possible to map an NDBM/GDBM file into an @code{awk} array.
  1296. X
  1297. X@item Single-character fields
  1298. XThe null string, @code{""}, as a field separator, will cause field
  1299. Xsplitting and the split function to separate individual characters.
  1300. XThus, @code{split(a, "abcd", "")} would yield @code{a[1] == "a"},
  1301. X@code{a[2] == "b"}, and so on.
  1302. X
  1303. X@item Fixed-length fields and records
  1304. XA mechanism may be provided to allow the specification of fixed length
  1305. Xfields and records.
  1306. X
  1307. X@item Regexp syntax
  1308. XThe @code{egrep} syntax for regular expressions, now specified
  1309. Xwith the @samp{-e} option, may become the default, since the
  1310. XPOSIX standard may specify this.
  1311. X
  1312. X@c this is @emph{very} long term --- not worth including right now.
  1313. X@ignore
  1314. X@item The C Comma Operator
  1315. XWe may add the C comma operator, which takes the form
  1316. X@code{@var{expr1},@var{expr2}}.  The first expression is evaluated, and the
  1317. Xresult is thrown away.  The value of the full expression is the value of
  1318. X@var{expr2}.@refill
  1319. X@end ignore
  1320. X@end table
  1321. X
  1322. X@node Improvements,, Future Extensions, Notes
  1323. X@appendixsec Suggestions for Improvements
  1324. X
  1325. XHere are some projects that would-be @code{gawk} hackers might like to take
  1326. Xon.  They vary in size from a few days to a few weeks of programming,
  1327. Xdepending on which one you choose and how fast a programmer you are.  Please
  1328. Xsend any improvements you write to the maintainers at the GNU
  1329. Xproject.@refill
  1330. X
  1331. X@enumerate
  1332. X@item
  1333. XState machine regexp matcher: At present, @code{gawk} uses the
  1334. Xbacktracking regular expression matcher from the GNU subroutine library.
  1335. XIf a regexp is really going to be used a lot of times, it is faster to
  1336. Xconvert it once to a description of a finite state machine, then run a
  1337. Xroutine simulating that machine every time you want to match the regexp.
  1338. XYou might be able to use the matching routines used by GNU @code{egrep}.
  1339. X
  1340. X@item
  1341. XCompilation of @code{awk} programs: @code{gawk} uses a Bison (YACC-like)
  1342. Xparser to convert the script given it into a syntax tree; the syntax
  1343. Xtree is then executed by a simple recursive evaluator.  Both of these
  1344. Xsteps incur a lot of overhead, since parsing can be slow (especially if
  1345. Xyou also do the previous project and convert regular expressions to
  1346. Xfinite state machines at compile time) and the recursive evaluator
  1347. Xperforms many procedure calls to do even the simplest things.@refill
  1348. X
  1349. XIt should be possible for @code{gawk} to convert the script's parse tree
  1350. Xinto a C program which the user would then compile, using the normal
  1351. XC compiler and a special @code{gawk} library to provide all the needed
  1352. Xfunctions (regexps, fields, associative arrays, type coercion, and so
  1353. Xon).@refill
  1354. X
  1355. XAn easier possibility might be for an intermediate phase of @code{awk} to
  1356. Xconvert the parse tree into a linear byte code form like the one used
  1357. Xin GNU Emacs Lisp.  The recursive evaluator would then be replaced by
  1358. Xa straight line byte code interpreter that would be intermediate in speed
  1359. Xbetween running a compiled program and doing what @code{gawk} does
  1360. Xnow.@refill
  1361. X
  1362. X@item
  1363. XAn error message section has not been included in this version of the
  1364. Xmanual.  Perhaps some nice beta testers will document some of the messages
  1365. Xfor the future.
  1366. X@end enumerate
  1367. X
  1368. X@node Glossary, Index , Notes, Top
  1369. X@appendix Glossary
  1370. X
  1371. X@table @asis
  1372. X@item Action
  1373. XA series of @code{awk} statements attached to a rule.  If the rule's
  1374. Xpattern matches an input record, the @code{awk} language executes the
  1375. Xrule's action.  Actions are always enclosed in curly braces.
  1376. X@xref{Actions}.@refill
  1377. X
  1378. X@item Amazing @code{awk} Assembler
  1379. XHenry Spencer at the University of Toronto wrote a retargetable assembler
  1380. Xcompletely as @code{awk} scripts.  It is thousands of lines long, including
  1381. Xmachine descriptions for several 8-bit microcomputers.  It is distributed
  1382. Xwith @code{gawk} and is a good example of a program that would have been
  1383. Xbetter written in another language.@refill
  1384. X
  1385. X@item Assignment
  1386. XAn @code{awk} expression that changes the value of some @code{awk}
  1387. Xvariable or data object.  An object that you can assign to is called an
  1388. X@dfn{lvalue}.  @xref{Assignment Ops}.@refill
  1389. X
  1390. X@item @code{awk} Language
  1391. XThe language in which @code{awk} programs are written.
  1392. X
  1393. X@item @code{awk} Program
  1394. XAn @code{awk} program consists of a series of @dfn{patterns} and
  1395. X@dfn{actions}, collectively known as @dfn{rules}.  For each input record
  1396. Xgiven to the program, the program's rules are all processed in turn.
  1397. X@code{awk} programs may also contain function definitions.@refill
  1398. X
  1399. X@item @code{awk} Script
  1400. XAnother name for an @code{awk} program.
  1401. X
  1402. X@item Built-in Function
  1403. XThe @code{awk} language provides built-in functions that perform various
  1404. Xnumerical and string computations.  Examples are @code{sqrt} (for the
  1405. Xsquare root of a number) and @code{substr} (for a substring of a
  1406. Xstring).  @xref{Built-in}.@refill
  1407. X
  1408. X@item Built-in Variable
  1409. XThe variables @code{ARGC}, @code{ARGV}, @code{ENVIRON},  @code{FILENAME},
  1410. X@code{FNR}, @code{FS}, @code{NF}, @code{IGNORECASE}, @code{NR}, @code{OFMT},
  1411. X@code{OFS}, @code{ORS}, @code{RLENGTH}, @code{RSTART}, @code{RS}, and
  1412. X@code{SUBSEP}, have special meaning to @code{awk}.  Changing some of them
  1413. Xaffects @code{awk}'s running environment.  @xref{Built-in Variables}.@refill
  1414. X
  1415. X@item C
  1416. XThe system programming language that most GNU software is written in.  The
  1417. X@code{awk} programming language has C-like syntax, and this manual
  1418. Xpoints out similarities between @code{awk} and C when appropriate.@refill
  1419. X
  1420. X@item Compound Statement
  1421. XA series of @code{awk} statements, enclosed in curly braces.  Compound
  1422. Xstatements may be nested.  @xref{Statements}.@refill
  1423. X
  1424. X@item Concatenation
  1425. END_OF_FILE
  1426.   if test 49614 -ne `wc -c <'./gawk.texinfo.06'`; then
  1427.     echo shar: \"'./gawk.texinfo.06'\" unpacked with wrong size!
  1428.   fi
  1429.   # end of './gawk.texinfo.06'
  1430. fi
  1431. if test -f './missing.d/strerror.c' -a "${1}" != "-c" ; then 
  1432.   echo shar: Will not clobber existing file \"'./missing.d/strerror.c'\"
  1433. else
  1434.   echo shar: Extracting \"'./missing.d/strerror.c'\" \(1264 characters\)
  1435.   sed "s/^X//" >'./missing.d/strerror.c' <<'END_OF_FILE'
  1436. X/*
  1437. X * strerror.c --- ANSI C compatible system error routine
  1438. X */
  1439. X
  1440. X/* 
  1441. X * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
  1442. X * 
  1443. X * This file is part of GAWK, the GNU implementation of the
  1444. X * AWK Progamming Language.
  1445. X * 
  1446. X * GAWK is free software; you can redistribute it and/or modify
  1447. X * it under the terms of the GNU General Public License as published by
  1448. X * the Free Software Foundation; either version 1, or (at your option)
  1449. X * any later version.
  1450. X * 
  1451. X * GAWK is distributed in the hope that it will be useful,
  1452. X * but WITHOUT ANY WARRANTY; without even the implied warranty of
  1453. X * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  1454. X * GNU General Public License for more details.
  1455. X * 
  1456. X * You should have received a copy of the GNU General Public License
  1457. X * along with GAWK; see the file COPYING.  If not, write to
  1458. X * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  1459. X */
  1460. X
  1461. Xextern int sys_nerr;
  1462. Xextern char *sys_errlist[];
  1463. X
  1464. X/* have to get right decl of sprintf early on */
  1465. X#ifndef BUFSIZ    /* stdio specific definition */
  1466. X#include <stdio.h>
  1467. X#endif
  1468. X
  1469. Xchar *
  1470. Xstrerror(n)
  1471. Xint n;
  1472. X{
  1473. X    static char mesg[30];
  1474. X
  1475. X    if (n < 0 || n > sys_nerr) {
  1476. X        sprintf (mesg, "Unknown error (%d)", n);
  1477. X        return mesg;
  1478. X    } else
  1479. X        return sys_errlist[n];
  1480. X}
  1481. END_OF_FILE
  1482.   if test 1264 -ne `wc -c <'./missing.d/strerror.c'`; then
  1483.     echo shar: \"'./missing.d/strerror.c'\" unpacked with wrong size!
  1484.   fi
  1485.   # end of './missing.d/strerror.c'
  1486. fi
  1487. if test -f './missing.d/tmpnam.c' -a "${1}" != "-c" ; then 
  1488.   echo shar: Will not clobber existing file \"'./missing.d/tmpnam.c'\"
  1489. else
  1490.   echo shar: Extracting \"'./missing.d/tmpnam.c'\" \(484 characters\)
  1491.   sed "s/^X//" >'./missing.d/tmpnam.c' <<'END_OF_FILE'
  1492. X/*
  1493. X * tmpnam - an implementation for systems lacking a library version
  1494. X *        this version does not rely on the P_tmpdir and L_tmpnam constants.
  1495. X */
  1496. X
  1497. X#ifndef NULL
  1498. X#define NULL    0
  1499. X#endif
  1500. X
  1501. Xstatic char template[] = "/tmp/gawkXXXXXX";
  1502. X
  1503. Xchar *
  1504. Xtmpnam(tmp)
  1505. Xchar *tmp;
  1506. X{
  1507. X    static char tmpbuf[sizeof(template)];
  1508. X    
  1509. X    if (tmp == NULL) {
  1510. X        (void) strcpy(tmpbuf, template);
  1511. X        (void) mktemp(tmpbuf);
  1512. X        return tmpbuf;
  1513. X    } else {
  1514. X        (void) strcpy(tmp, template);
  1515. X        (void) mktemp(tmp);
  1516. X        return tmp;
  1517. X    }
  1518. X}
  1519. END_OF_FILE
  1520.   if test 484 -ne `wc -c <'./missing.d/tmpnam.c'`; then
  1521.     echo shar: \"'./missing.d/tmpnam.c'\" unpacked with wrong size!
  1522.   fi
  1523.   # end of './missing.d/tmpnam.c'
  1524. fi
  1525. echo shar: End of archive 7 \(of 16\).
  1526. cp /dev/null ark7isdone
  1527. MISSING=""
  1528. for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ; do
  1529.     if test ! -f ark${I}isdone ; then
  1530.     MISSING="${MISSING} ${I}"
  1531.     fi
  1532. done
  1533. if test "${MISSING}" = "" ; then
  1534.     echo You have unpacked all 16 archives.
  1535.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1536. else
  1537.     echo You still must unpack the following archives:
  1538.     echo "        " ${MISSING}
  1539. fi
  1540. exit 0
  1541. exit 0 # Just in case...
  1542.